package xcmg.device.service.warehouse;

import com.github.pagehelper.PageInfo;
import yb.ecp.fast.infra.util.PageHelperPlus;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xcmg.device.dao.entity.warehouse.WarehouseInboundDO;
import xcmg.device.dao.entity.warehouse.WarehouseInboundDetailDO;
import xcmg.device.dao.mapper.warehouse.WarehouseInboundDetailMapper;
import xcmg.device.infra.ErrorCode;
import xcmg.device.service.vo.warehouse.UpdatePrintNumVO;
import xcmg.device.service.vo.warehouse.WarehouseInboundDetailVO;
import xcmg.device.service.vo.warehouse.WarehouseInboundVO;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.util.ListUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WarehouseInboundDetailService {

    @Autowired
    private WarehouseInboundDetailMapper warehouseInboundDetailMapper;

    @Autowired
    private WarehouseInboundService warehouseInboundService;

    @Autowired
    private FastGenClient fastGenClient;

    /**
     * @Author: WangKe
     * @Description: 新增入库详情记录
     * @Date: 15:19 2018/1/17 0017
     */
    public ErrorCode add(WarehouseInboundDetailVO warehouseInboundDetailVO){
        ActionResult<String> textResult = fastGenClient.textGuid();
        if (textResult.getCode() != ErrorCode.Success.getCode())
        {
            return ErrorCode.IllegalArument;
        }
        WarehouseInboundDetailDO warehouseInboundDetailDO = new WarehouseInboundDetailDO();
        BeanUtils.copyProperties(warehouseInboundDetailVO, warehouseInboundDetailDO);

        warehouseInboundDetailDO.setId(textResult.getValue());
        warehouseInboundDetailDO.setStatus(0);
        warehouseInboundDetailDO.setCreateDate(new Date());
        warehouseInboundDetailDO.setPrintNum(BigDecimal.ZERO);
        warehouseInboundDetailDO.setPrintState(0);
        boolean isSuccess = warehouseInboundDetailMapper.insert(warehouseInboundDetailDO)>0;
        return isSuccess? ErrorCode.Success: ErrorCode.Failure;
    }

    /**
     * @Author: WangKe
     * @Description: 根据入库单号查找入库记录详情列表
     * @Date: 2018/1/19 0019
     */
    public List<WarehouseInboundDetailDO> findByInboundOrder(String inboundOrder, String orgId){
        if(inboundOrder == null){
            return new ArrayList<WarehouseInboundDetailDO>();
        }
        return warehouseInboundDetailMapper.findByInboundOrder(inboundOrder, orgId);
    }

    /**
     * @Author: WangKe
     * @Description: 根据入库业务单据号查找入库详情列表
     * @Date: 2018/2/2 0002
     */
    public List<WarehouseInboundDetailDO> findByBusinessOrder(String businessOrder, String orgId){
        if(businessOrder == null){
            return new ArrayList<WarehouseInboundDetailDO>();
        }
        return warehouseInboundDetailMapper.findByBusinessOrder(businessOrder, orgId);
    }

    /**
     * @Author: WangKe
     * @Description: 根据条件查询入库详情列表
     * @Date: 2018/2/2 0002
     */
    public PageCommonVO list(SearchCommonVO<WarehouseInboundDetailVO> condition) {
        PageCommonVO<WarehouseInboundDetailVO> pageCommonVO = new PageCommonVO();
        PageHelperPlus.orderBy("create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<WarehouseInboundDetailDO> doList = warehouseInboundDetailMapper.list(condition.getFilters());
        List<WarehouseInboundDetailVO> voList = new ArrayList<WarehouseInboundDetailVO>();
        for (WarehouseInboundDetailDO entity : doList) {
            WarehouseInboundDetailVO model = new WarehouseInboundDetailVO();
            BeanUtils.copyProperties(entity, model);
            voList.add(model);
        }
        pageCommonVO.setPageInfo(new PageInfo(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    /**
     * @Author: WangKe
     * @Description: 根据入库单号删除入库详情记录
     * @Date: 2018/1/23 0023
     */
    public ErrorCode deleteByInboundOrder(String inboundOrder, String orgId){
        int i = warehouseInboundDetailMapper.deleteByInboundOrder(inboundOrder, orgId);
        return i>0? ErrorCode.Success: ErrorCode.WarehouseIdError;
    }

    /**
     * @Author: WangKe
     * @Description: 根据入库单号删除入库详情记录
     * @Date: 2018/1/26 0026
     */
    public ErrorCode deleteByInboundOrderList(List<String> orderList, String orgId){
        int i = warehouseInboundDetailMapper.removeByInOrderList(orderList, orgId);
        return i>0? ErrorCode.Success: ErrorCode.WarehouseIdError;
    }

    /**
     * @Author: WangKe
     * @Description: 增加入库记录时，更新入库主表和入库详情表
     * @Date: 2018/1/25 0025
     */
    public Map<String, BigDecimal> updateByInbound(String inboundOrder, String materialNo, BigDecimal amount, Integer rowNo, String orgId)throws Exception{
        Map<String, BigDecimal> map = new HashMap<>();
        map.put("success", BigDecimal.ZERO);
        WarehouseInboundDetailVO vo = new WarehouseInboundDetailVO();
        vo.setInboundOrder(inboundOrder);
        vo.setMaterialNo(materialNo);
        vo.setOrgId(orgId);
        vo.setRowNo(rowNo);
        List<WarehouseInboundDetailDO> list = warehouseInboundDetailMapper.list(vo);
        if(ListUtil.isNullOrEmpty(list)){
            return map;
        }
        WarehouseInboundDetailDO entity = list.get(0);
        for(WarehouseInboundDetailDO detailDO : list){
            if(detailDO.getRealAmount().add(amount).compareTo(detailDO.getAmount()) <= 0){
                entity = detailDO;
            }
        }
        map.put("rowNo", entity.getRowNo()==null?BigDecimal.ZERO:BigDecimal.valueOf(entity.getRowNo()));
        BigDecimal totalAmount = entity.getAmount();
        BigDecimal realAmount = entity.getRealAmount();
        BigDecimal sub = amount.add(realAmount);

        boolean success;
        if(sub.compareTo(totalAmount) > 0){
            throw new Exception("实际入库数量不能大于计划入库数量");
        }else if(sub.compareTo(totalAmount) == 0){
            entity.setRealAmount(sub);
            entity.setStatus(2);
        }else{
            entity.setRealAmount(sub);
            entity.setStatus(1);
        }
        map.put("realAmount", entity.getRealAmount());
        map.put("singleState", new BigDecimal(entity.getStatus()));
        map.put("totalState", BigDecimal.ZERO);
        success = warehouseInboundDetailMapper.updateByPrimaryKeySelective(entity)>0;
        if(success){
            boolean temp = true;
            boolean finishFlag = false;//强制完成标记： false非强制，true强制完成
            vo = new WarehouseInboundDetailVO();
            vo.setInboundOrder(inboundOrder);
            vo.setOrgId(orgId);
            list = warehouseInboundDetailMapper.list(vo);
            for(WarehouseInboundDetailDO model : list){
                if(model.getStatus()==3)
                {
                    finishFlag=true;//强制完成
                }
                if(model.getAmount() != null && !model.getAmount().equals(model.getRealAmount()) && model.getStatus()!=3){
                    temp = false;//部分完成
                    break;
                }
            }

            WarehouseInboundVO inboundVO = new WarehouseInboundVO();
            inboundVO.setInboundOrder(entity.getInboundOrder());
            inboundVO.setOrgId(orgId);
            List<WarehouseInboundDO> inboundList = warehouseInboundService.list(inboundVO);
            if(ListUtil.isNullOrEmpty(inboundList)){
                return map;
            }
            WarehouseInboundDO inboundDO = inboundList.get(0);

            if (temp && finishFlag)//完成状态，其中有零件是强制结单，故单据状态为强制完成
            {
                inboundDO.setStatus(3);
            }
            else if (temp && !finishFlag)
            {
                inboundDO.setStatus(2);
            }
            else
            {
                inboundDO.setStatus(1);
            }
            map.put("totalState", new BigDecimal(inboundDO.getStatus()));
            success = warehouseInboundService.updateByPK(inboundDO);
            map.put("success", new BigDecimal(success?1:0));
        }
        return map;
    }

    /**
     * @Author: WangKe
     * @Description: 根据业务单号和零件号更新打印状态
     * @Date: 2018/2/2 0002
     */
    public ErrorCode updatePrintNum(List<UpdatePrintNumVO> list, String orgId){
        if(ListUtil.isNullOrEmpty(list)){
            return ErrorCode.AbnormalDetailArgumentError;
        }
        for(UpdatePrintNumVO model : list){
            WarehouseInboundDetailVO vo = new WarehouseInboundDetailVO();
            vo.setBusinessOrder(model.getBusinessOrder());
            vo.setMaterialNo(model.getMaterialsNo());
            vo.setOrgId(orgId);
            vo.setRowNo(model.getRowNo());
            List<WarehouseInboundDetailDO> detailDOList = warehouseInboundDetailMapper.list(vo);
            if(ListUtil.isNullOrEmpty(detailDOList)){
                return ErrorCode.AbnormalDetailNotFound;
            }
            WarehouseInboundDetailDO entity = detailDOList.get(0);
            BigDecimal oldNum = entity.getPrintNum()==null?BigDecimal.ZERO:entity.getPrintNum();
            BigDecimal newNum = oldNum.add(model.getPrintNum());
            if(entity.getAmount().compareTo(newNum) > 0){
                entity.setPrintState(1);
            }else if(entity.getAmount().compareTo(newNum) <= 0){
                entity.setPrintState(2);
            }
            entity.setPrintNum(newNum);
            warehouseInboundDetailMapper.updateByPrimaryKeySelective(entity);
        }
        return ErrorCode.Success;
    }
}
